package cloudoer.su.service.impl;

import cloudoer.su.base.impl.BaseServiceImpl;
import cloudoer.su.entity.Menu;
import cloudoer.su.entity.Role;
import cloudoer.su.entity.User;
import cloudoer.su.exception.ServiceException;
import cloudoer.su.service.RoleService;
import cloudoer.su.utils.ExcelUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service("roleService")
@Transactional
public class RoleServiceImpl extends BaseServiceImpl implements RoleService {
    public List<Role> getAll(String q) {
        if (StringUtils.isNotBlank(q)){
            return roleDao.getByLikeName(q);
        }
        return roleDao.getAll();
    }

    public List<Role> getByPage(int pageNo, int pageSize) {
        return roleDao.getByPage(pageNo, pageSize);
    }

    public Role getById(String id) {
        return (Role) roleDao.getById(id);
    }

    public Role getByNumber(String number) {
        return (Role) roleDao.getByNumber(number);
    }

    public String add(Role role) {
        return roleDao.add(role);
    }

    public void update(Role role) {
        Role r = (Role) roleDao.getById(role.getId());
        if (r == null){
            throw new ServiceException("修改失败，参数错误");
        }
        r.setName(role.getName());
        r.setIntroduce(role.getIntroduce());
        r.setNumber(role.getNumber());
        r.setState(role.getState());
    }

    public void delete(String id) {
        Role r = (Role) roleDao.getById(id);
        if (r == null){
            throw new ServiceException("删除失败，参数错误");
        }
        roleDao.delete(id);
    }

    public String importFile(File file) throws ServiceException {
        HSSFWorkbook workbook = null;
        StringBuffer msg = new StringBuffer();
        try {
            workbook = new HSSFWorkbook(new FileInputStream(file));
            HSSFSheet sheet = workbook.getSheetAt(0);
            int cont = sheet.getLastRowNum()+1;
            Role r = null;
            int successCount = 0;
            int errorCount = 0;
            for (int i = 1; i < cont; i++){
                try {
                    r = new Role();
                    r.setName(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(0)));
                    r.setNumber(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(1)));
                    r.setIntroduce(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(2)));
                    r.setState(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(3)));
                    roleDao.add(r);
                    successCount ++ ;
                    if (i+1%20==0){
                        roleDao.getSession().flush();
                        roleDao.getSession().clear();
                    }
                }catch (ServiceException e){
                    errorCount++;
                    msg.append("[第"+(i+1)+"行]原因:" + e.getErrorMsg());
                    msg.append("<br/>");
                }catch (Exception e){
                    errorCount++;
                    msg.append("[第"+(i+1)+"行]原因:不明...<br/>");
                }
            }
            msg.insert(0,"文件上传成功<br/>导入成功:"+ successCount +"条" + "<br/>导入失败:"+errorCount+ "条 <br/>记录<br/>");
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("导入失败，解析文件错误，请检查文件格式");
        }
        return msg.toString();
    }

    public void exportFile(OutputStream os) throws Exception {
        List<Role> list = teacherDao.getAll();
        // 创建工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建工作表
        HSSFSheet sheet = workbook.createSheet("sheet1");
        //创建一行
        HSSFRow rows = sheet.createRow(0);
        //创建这一行的一个单元格
        rows.createCell(0).setCellValue("角色名称");
        rows.createCell(1).setCellValue("角色编号");
        rows.createCell(2).setCellValue("角色说明");
        rows.createCell(3).setCellValue("状态");
        for (int i = 0; i < list.size(); i++){
            rows = sheet.createRow(i+1);
            rows.createCell(0).setCellValue(list.get(i).getName());
            rows.createCell(1).setCellValue(list.get(i).getNumber());
            rows.createCell(2).setCellValue(list.get(i).getIntroduce());
            rows.createCell(3).setCellValue(list.get(i).getState());
        }
        workbook.write(os);
    }

    public Set<User> getUsers(String id) {
        Role r = (Role) roleDao.getById(id);
        if (r == null){
            throw new ServiceException("参数错误");
        }
        if (r.getUsers() == null){
            return new HashSet<User>();
        }
        return r.getUsers();
    }

    public Set<Menu> getMenus(String id) {
        Role r = (Role) roleDao.getById(id);
        if (r == null){
            throw new ServiceException("参数错误");
        }
        if (r.getMenus() == null){
            return new HashSet<Menu>();
        }
        return r.getMenus();
    }

    public void setMenus(String id, String[] menuIds) {
        Role r = (Role) roleDao.getById(id);
        if (r == null){
            throw new ServiceException("参数错误，设置失败");
        }
        r.getMenus().clear();
        for (String menuId : menuIds){
            Menu m = (Menu) menuDao.getById(menuId);
            if (m != null){
                r.getMenus().add(m);
            }
        }
    }

    public void deleteMenus(String id, String menuId) {
        Role r = (Role) roleDao.getById(id);
        Menu m = (Menu) menuDao.getById(menuId);
        if (r == null || m == null){
            throw new ServiceException("参数错误，删除失败");
        }
        r.getMenus().remove(m);
    }

    public void setUsers(String id, String[] userIds){
        Role r = (Role) roleDao.getById(id);
        if (r == null){
            throw new ServiceException("参数错误，添加失败");
        }
        if (userIds != null){
            r.getUsers().clear();
            for(String userId : userIds){
                User u = (User) userDao.getById(userId);
                if (u != null){
                    r.getUsers().add(u);
                }
            }
        }
    }

    public void deleteUsers(String id, String userId){
        Role r = (Role) roleDao.getById(id);
        User u = (User) userDao.getById(userId);
        if (r == null || u ==null){
            throw new ServiceException("参数错误，删除失败");
        }
        r.getUsers().remove(u);
    }

    public int getCount() {
        return roleDao.getCount();
    }
}
